package indi.zhang.rabbitmq.utils;

import com.alibaba.fastjson.JSON;
import com.yomahub.tlog.core.mq.TLogMqWrapBean;
import indi.zhang.common.base.Result;
import indi.zhang.mq.MessageContent;
import indi.zhang.mq.api.Producer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
public class RabbitMqProducer implements Producer {
    private final RabbitTemplate rabbitTemplate;

    @Override
    public Result<Object> sendEventMessageTLog(MessageContent messageContent) {
        try {
            TLogMqWrapBean<MessageContent> tLogMqWrap = new TLogMqWrapBean<>(messageContent);
            String tLogMqWrapString = JSON.toJSONString(tLogMqWrap);
            rabbitTemplate.convertAndSend(messageContent.getTopic(), tLogMqWrapString);
            log.info("消息发送成功 topic[{}],data[{}]",messageContent.getTopic(),messageContent);
        } catch (Exception e) {
            log.error("消息发送失败 topic[{}]],data[{}]",messageContent.getTopic(),messageContent);
            return Result.error();
        }
        return Result.success();
    }

    /**
     * 通用message发送接口
     * @param messageContent
     * @return
     */
    @Override
    public Result<Object> sendEventMessage(MessageContent messageContent) {
        try {
            String messageContentString = JSON.toJSONString(messageContent);
            System.out.println("Sender :"+ messageContentString);
            rabbitTemplate.convertAndSend(messageContent.getTopic(), messageContentString);
            log.info("消息发送成功 topic[{}],data[{}]",messageContent.getTopic(),messageContent);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("消息发送失败 topic[{}]],data[{}]",messageContent.getTopic(),messageContent);
            return Result.error();
        }
        return Result.success();
    }
}
